package _3_TwoPointers;

import java.util.Arrays;
import java.util.List;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;

public class A57_twoSum {
    //超出时间限制 用list集合来做
    public int[] twoSum(int[] nums, int target) {
        List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
        for (int i = 0; i < nums.length; i++) {
            int aim = target - nums[i];
            if (aim > 0 && list.indexOf(aim) != -1 ){
                int[] ints = new int[2];
                ints[0] = list.get(i);
                ints[1] = aim;
                return ints;
            }
        }
        return null;
    }
    //尝试下用数组来做,原理和上面差不多
    public int[] twoSum2(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            int aim = target - nums[i];
            if (aim > 0 && Arrays.stream(nums).anyMatch(value -> value == aim)){
                int[] ints = new int[2];
                ints[0] = nums[i];
                ints[1] = aim;
                return ints;
            }
        }
        return null;
    }
    //指针
    public int[] twoSum3(int[] nums, int target) {
        int i = 0, j = nums.length - 1;
        while(i < j) {
            int s = nums[i] + nums[j];
            if(s < target) i++;
            else if(s > target) j--;
            else return new int[] { nums[i], nums[j] };
        }
        return new int[0];
    }


}
